<template>
  <div class="analysis-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="analysis-card">
          <template #header>
            <span>答卷来源分析（广西地区）</span>
          </template>
          <el-tabs v-model="activeChart" type="card">
            <el-tab-pane label="时间段分布" name="time">
              <el-date-picker
                v-model="timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="renderCharts"
                style="margin-bottom: 20px"
              />
              <div ref="timeChart" style="height: 400px;"></div>
            </el-tab-pane>
            <el-tab-pane label="来源网站" name="source">
              <div ref="sourceChart" style="height: 400px;"></div>
            </el-tab-pane>
            <el-tab-pane label="地区分布" name="region">
              <div ref="regionChart" style="height: 400px;"></div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElCard, ElTabs, ElTabPane, ElDatePicker, ElRow, ElCol } from 'element-plus';

const timeChart = ref(null);
const sourceChart = ref(null);
const regionChart = ref(null);
const activeChart = ref('time');
const timeRange = ref([new Date('2023-10-01'), new Date('2023-10-08')]);

// 模拟数据
const timeDistribution = {
  timeLabels: ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"],
  counts: [5, 10, 8, 20, 25, 18, 12, 7]
};

const sourceDistribution = {
  sources: [
    { source: "微信", count: 45 },
    { source: "企业微信", count: 30 },
    { source: "QQ", count: 15 },
    { source: "微博", count: 5 },
    { source: "直接访问", count: 5 }
  ]
};

const regionDistribution = {
  regions: [
    { name: "南宁市", count: 120 },
    { name: "柳州市", count: 85 },
    { name: "桂林市", count: 75 },
    { name: "梧州市", count: 60 },
    { name: "北海市", count: 45 },
    { name: "防城港市", count: 30 },
    { name: "钦州市", count: 25 },
    { name: "贵港市", count: 40 },
    { name: "玉林市", count: 50 },
    { name: "百色市", count: 35 },
    { name: "贺州市", count: 20 },
    { name: "河池市", count: 15 },
    { name: "来宾市", count: 10 },
    { name: "崇左市", count: 5 }
  ]
};

// 渲染时间分布图表
const renderTimeChart = () => {
  const chart = echarts.init(timeChart.value);
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: timeDistribution.timeLabels,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: timeDistribution.counts,
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#409EFF'
      }
    }]
  });
};

// 渲染来源网站图表
const renderSourceChart = () => {
  const chart = echarts.init(sourceChart.value);
  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: sourceDistribution.sources.map(item => item.source)
    },
    series: [
      {
        name: '来源分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: sourceDistribution.sources.map(item => ({
          value: item.count,
          name: item.source
        }))
      }
    ]
  });
};

// 渲染地区分布图表
const renderRegionChart = () => {
  const chart = echarts.init(regionChart.value);
  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: regionDistribution.regions.map(item => item.name)
    },
    series: [
      {
        name: '答卷数量',
        type: 'bar',
        data: regionDistribution.regions.map(item => item.count),
        itemStyle: {
          color: function(params) {
            // 为不同地区设置不同颜色
            const colorList = [
              '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
              '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570',
              '#c4ccd3', '#f05b72', '#ef5b9c', '#f47920'
            ];
            return colorList[params.dataIndex];
          }
        }
      }
    ]
  });
};

// 渲染所有图表
const renderCharts = () => {
  renderTimeChart();
  renderSourceChart();
  renderRegionChart();
};

onMounted(() => {
  nextTick(() => {
    renderCharts();
  });
});

// 监听窗口变化，重新调整图表大小
window.addEventListener('resize', function() {
  if (timeChart.value) {
    echarts.getInstanceByDom(timeChart.value)?.resize();
  }
  if (sourceChart.value) {
    echarts.getInstanceByDom(sourceChart.value)?.resize();
  }
  if (regionChart.value) {
    echarts.getInstanceByDom(regionChart.value)?.resize();
  }
});
</script>

<style scoped>
.analysis-container {
  padding: 10px;
}

.analysis-card {
  margin-bottom: 20px;
}

.chart-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>